package LeetCode._01算法入门.day07广度深度优先搜索;

import org.junit.Test;
import utils.MyPrintUtil;

/**
 * @author 挚爱之夕
 * @date 2022-02-27 - 02 - 27 - 10:51
 * @Description 东南西北连在一起的算作一个岛屿 对角线不算 求最大岛屿面积
 * 1 表示土地 0 表示海洋
 * @Version 中等
 */
public class _695岛屿的最大面积 {
    @Test
    public void solve(){
        int[][] grid = {
                {0,0,1,0,0,0,0,1,0,0,0,0,0},
                {0,0,0,0,0,0,0,1,1,1,0,0,0},
                {0,1,1,0,1,0,0,0,0,0,0,0,0},
                {0,1,0,0,1,1,0,0,1,0,1,0,0},
                {0,1,0,0,1,1,0,0,1,1,1,0,0},
                {0,0,0,0,0,0,0,0,0,0,1,0,0},
                {0,0,0,0,0,0,0,1,1,1,0,0,0},
                {0,0,0,0,0,0,0,1,1,0,0,0,0}
        };
        System.out.println(maxAreaOfIsland(grid));
        MyPrintUtil.printArray(grid);
    }
    public int maxAreaOfIsland(int[][] grid) {
        int max = 0;
        int count;
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(grid[i][j] == 1){
                    count = def(grid, i, j, 1);
                    max = Math.max(max, count);
                }
            }
        }
        return max;
    }

    /**
     * 返回该岛屿的最大面积
     * @param grid 表示岛屿的二维数组
     * @param i 起始x坐标
     * @param j 起始y坐标
     * @param val 表示土壤的数值 -- 1
     * @return 这个岛屿的面积
     */
    public int def(int[][] grid, int i, int j, int val){
        //终止条件
        if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != val)
            return 0;
        //计数
        int count = 1;
        //表示已经计算过
        grid[i][j] = -1;
        //上
        count += def(grid, i, j - 1, val);
        //下
        count += def(grid, i, j + 1, val);
        //左
        count += def(grid, i - 1, j, val);
        //右
        count += def(grid, i + 1, j, val);
        return count;
    }
}
